<?php
// +----------------------------------------------------------------------
// | 会员常规操作
// +----------------------------------------------------------------------

namespace User\Controller;
use Common\Controller\Base;
use Common\Model\Model;
use Think\Controller;

class IndexController extends UserbaseController {

    protected function _initialize(){
        parent::_initialize();
        $this->assign('usernav', $this->getUserNav());
    }

    /**
     * 会员登录页显示
     */
    public function index(){
        if(IS_POST){
            //更新用户资料
            $post=I('post.');
            if(empty($post)){
                $this->error('信息更新失败!');
            }
            $result=M('User')->where(array('userid'=>$this->userid))->save($post);
            if($result!==false){
                $this->success('您的资料更新成功!');
            }else{
                $this->error('您的资料更新失败');
            }
        }else{
            //省份
            $this->province=M('Province')->field('province_id,province_name')->select();
            if(!empty($this->userinfo['ucity']) && !empty($this->userinfo['uprovince'])){
                $this->ucity=M('City')->where(array('province_id'=>$this->userinfo['uprovince']))->select();
            }
            if(!empty($this->userinfo['ucity']) && !empty($this->userinfo['uarea'])){
                $this->uarea=M('Area')->where(array('city_id'=>$this->userinfo['ucity']))->select();
            }
            //数量统计
            //烘焙作品数
            $this->hbworksnum=getCount('Works',array('userid'=>$this->userid,'status'=>true));
            //随拍作品
            $this->spworksnum=getCount('Suipai',array('userid'=>$this->userid,'status'=>true));
            //留言数
            $this->msgnum=getCount('UserMessage',array('userid'=>$this->userid,'status'=>true));
            //试用报告数
            $this->reportnum=getCount('TryReport',array('userid'=>$this->userid,'status'=>true));
            //收藏作品数
            $this->favoritenum=getCount('UserFavorite',array('userid'=>$this->userid,'status'=>true));
            //修改头像密钥
            $this->auth_key = urlencode(\Libs\Util\Encrypt::authcode($this->userid, ''));
        }
        $this->display();

    }

    //我的订单
    public function order(){
        $this->display();
    }

    //试用记录
    public function trylist(){

        $model=M('TryApply');
        $status=I('get.st');
        $this->assign('act'.$status,' class="act"');
        $where['userid']=$this->userid;
        if(isset($_GET['st']) && $_GET['st']==0){
            $where['status']=false;
        }elseif(isset($_GET['st'])){
            $where['status']=$status;
        }
        $linkurl=isset($_GET['st'])?'&st='.$status:'';
        $count = $model->where($where)->count();
        $page = $this->Pages($count, 10);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = __APP__.'/user/index/trylist/'.$pageurl.$linkurl;

        $trylist=$model->where($where)->order('id DESC')->limit($page->firstRow . ',' . $page->listRows)->select();

        foreach($trylist as $k=>$v){
            $trylist[$k]['tryitem']=M('TryItems')->field('title,image')->where(array('tryid'=>$v['tryid']))->find();
            $trylist[$k]['reportid']=M('TryReport')->where(array('tryid'=>$v['tryid'],'userid'=>$this->userid))->getField('id');
        }
        $this->assign('trylist',$trylist);
        $this->assign("Page", $page->show());
        $this->display();

    }

    //试用报告
    public function report(){
        $data=M('TryReport')->where(array('userid'=>$this->userid))->select();
        $this->assign('list',$data);
        $this->display();
    }


    //删除试用记录
    public function deltry(){
        $tryid=I('infoid');
        if(empty($tryid)){
            $this->error('删除出错,请稍候再试!');
        }
        $try=M('TryApply')->field('userid,status,tryid')->where(array('id'=>$tryid))->find();
        if($try['userid']!=$this->userid || $try['status']==true){
            $this->error('您无权删除该试用!');
        }
        $result=M('TryApply')->delete($tryid);
        if($result){
            M('TryItems')->where(array('tryid'=>$try['tryid']))->setDec('requestnum');
            $this->success('<span>删除成功,正在为您转向...</span>');
        }else{
            $this->error('<span>删除失败,请稍候再试!</span>');
        }
    }

    //积分换礼
    public function jifen(){
        $model=M('GiftsApply');
        $status=I('get.st');
        $this->assign('act'.$status,' class="act"');
        $where['userid']=$this->userid;
        if(isset($_GET['st']) && $_GET['st']==0){
            $where['status']=false;
        }elseif(isset($_GET['st'])){
            $where['status']=$status;
        }
        $linkurl=isset($_GET['st'])?'&st='.$status:'';
        $count = $model->where($where)->count();
        $page = $this->Pages($count, 10);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = __APP__.'/user/index/jifen/'.$pageurl.$linkurl;

        $list=$model->where($where)->order('id DESC')->limit($page->firstRow . ',' . $page->listRows)->select();
        foreach($list as $k=>$v){
            $list[$k]['gifts']=M('Gifts')->field('title,image')->where(array('id'=>$v['giftid']))->find();
        }
        $this->assign('list',$list);
        $this->assign("Page", $page->show());
        $this->display();

    }

    //删除兑换记录
    public function deljifen(){
        $id=I('infoid');
        if(empty($id)){
            $this->error('删除出错,请稍候再试!');
        }
        $gift=M('GiftsApply')->field('userid,status,giftid')->where(array('id'=>$id))->find();
        if($gift['userid']!=$this->userid || $gift['status']==true){
            $this->error('您无权删除该试用!');
        }
        $result=M('GiftsApply')->delete($id);
        if($result){
            $needjf=M('Gifts')->where(array('id'=>$gift['giftid']))->getField('needjf');
            M('User')->where(array('userid'=>$gift['userid']))->setInc('upoint',$needjf);
            $this->success('<span>删除成功,正在为您转向...</span>');
        }else{
            $this->error('<span>删除失败,请稍候再试!</span>');
        }
    }


    //退出
    public function logout() {
        service("Passport")->logoutLocal();
        session("connect_openid", NULL);
        session("connect_app", NULL);
        $backurl=$_SERVER['HTTP_REFERER'];
        cookie('backurl',null);
        $this->success("您已成功退出成管理系统！", U($backurl));
    }

    //获取市
    public function getcity(){
        $pid=I('get.pid');
        $citylist=M('City')->where(array('province_id'=>$pid))->select();
        foreach($citylist as $k=>$v){
            $citylist[$k]['id']=$v['city_id'];
            $citylist[$k]['name']=$v['city_name'];
        }
        echo json_encode($citylist);
    }

    //获取地区
    public function getarea(){
        $pid=I('get.pid');
        $arealist=M('Area')->where(array('city_id'=>$pid))->select();
        foreach($arealist as $k=>$v){
            $arealist[$k]['id']=$v['area_id'];
            $arealist[$k]['name']=$v['area_name'];
        }
        echo json_encode($arealist);
    }

    //头像设置
    public function uavatar() {

        $auth_data = urlencode(\Libs\Util\Encrypt::authcode($this->userid, ''));
        $upurl = CONFIG_SITEURL_MODEL . 'index.php?m=user&c=index&a=uploaduavatar&authkey=' . $auth_data;
        $html = '<script type="text/javascript">
swfobject.addDomLoadEvent(function () {
    var swfFullAvatar = new fullAvatarEditor("myContent", {
        id: \'swf\',
        upload_url: \'' . $upurl . '\',
        avatar_sizes:"100*100",
        avatar_scale:2,
        avatar_sizes_desc:"200*200像素",
        src_upload: 1
    }, fullAvatarCallback);
});
</script>';

        $this->assign('user_avatar', $html);
        $this->display();
    }


    //保存用户头像
    public function uploaduavatar() {
        $auth_data = \Libs\Util\Encrypt::authcode(str_replace(' ', '+', $_GET['authkey']), 'DECODE');
        if ($auth_data != $this->userid) {
            exit(json_encode(array(
                'success' => false,
                'msg' => '身份验证失败！',
            )));
        }
        //头像保存目录
        $dir = C("UPLOADFILEPATH") . service("Passport")->getAvatarPath($this->userid);
        //实例化上传类
        $UploadFile = new \UploadFile(array(
            'allowExts' => array('jpg'),
            'uploadReplace' => true,
        ));
        //上传列表 120,90,45,30
        $upList = array('__avatar1');
        //保存文件名
        $upNameList = array('200x200');
        //路径
        $dir = C("UPLOADFILEPATH").'user/'.date('y').'/'.date('m').'/'.date('d').'/';
        $savepath = C("UPLOADSAVEPATH").'user/'.date('y').'/'.date('m').'/'.date('d').'/';

        foreach ($upList as $i => $key) {
            if (!isset($_FILES[$key])) {
                continue;
            }
            $_FILES[$key]['name'] .= '.jpg';
            //设置保存文件名
            $UploadFile->saveRule = $this->userid . '_' . $upNameList[$i];
            //上传头像
            $file = $UploadFile->uploadOne($_FILES[$key], $dir);
            if ($file === false) {
                exit(json_encode(array(
                    'success' => false,
                    'msg' => $UploadFile->getErrorMsg(),
                )));
                break;
            } else {
                service('Attachment')->movingFiles($file['savepath'] . $file['savename'], $file['savepath'] . $file['savename']);
                $data['uavatar']=$savepath.$file[0]['savename'];
                $result=M('User')->where(array('userid'=>$this->userid))->save($data);
            }
        }
        //上传结束
        exit(json_encode(array(
            'success' => true,
            'avatarUrls' => array(),
        )));
    }


    //提交上传头像--失效
    public function uphead() {
        $auth_data = \Libs\Util\Encrypt::authcode(str_replace(' ', '+', $_GET['authkey']), 'DECODE');
        if ($auth_data != $this->userid) {
            $this->error('身份验证失败!');
        }

        //实例化上传类
        $UploadFile = new \UploadFile(array(
            'allowExts' => array('jpg','gif','png'),
            'thumb' => true,
            'dateFormat' => 'y/m/d',
            'thumbRemoveOrigin'=>true,
            'thumbMaxWidth' => '180', // 缩略图最大宽度
            'thumbMaxHeight' => '180', // 缩略图最大高度
        ));
        $savepath = D('Upload/Files')->getFilePath('user', $UploadFile->dateFormat, time());
        $dir = C("UPLOADFILEPATH") .service("Passport")->getAvatarPath($this->userid) ;

        $file = $UploadFile->uploadOne($_FILES['uavatar'],$savepath);
        if ($file === false) {
            $this->error($UploadFile->getErrorMsg());
            exit;
        } else {
            service('Attachment')->movingFiles($file['getExtpath'] . $file['savename'], $file['getExtpath'] . $file['savename']);
            $data['uavatar']=$savepath.$file[0]['savename'];
            $result=M('User')->where(array('userid'=>$this->userid))->save($data);
            if($result){
                $this->success('头像更新成功');
            }else{
                $this->error('头像更新失败');
            }
        }
    }

    //添加报告页面
    public function addreport(){
        if(IS_POST){
            $post = I('post.');
            if(empty($post['content'])){
                $this->error('请填写试用报告简介');
            }
            $info=$post['image'];

            if(empty($info[0])){
                $this->error('请至少上传一张图片');
            }
            if ($info) { // 保存附件信息
                for($i=0;$i<count($info);$i++){
                    if($i==0){
                        $post['image']=$info[0];
                    }else{
                        $otherpic.=$info[$i].'|';
                    }
                }
                $post['otherpic']=substr($otherpic,0,strlen($otherpic)-1);
            }

            $post['cateid']=M('TryItems')->where(array('tryid'=>$post['tryid']))->getField('cateid');
            $post['create_time']=time();
            $post['userid']=$this->userid;
            $post['status']=true;
            $result=M('TryReport')->add($post);
            if($result){
                M('TryItems')->where(array('tryid'=>$post['tryid']))->setInc('iffinish',1);
                $this->success('试用报告发布成功',U('/user/index/report'));
            }else{
                $this->error('试用报告发布失败,请稍候再试!');
            }

        }else{
            $data['tryid']=I('get.id');
            $data['title']=M('TryItems')->where(array('tryid'=>$data['tryid']))->getField('title');
            $this->assign('data',$data);
            $this->display();
        }
    }

    //编辑试用报告
    public function editreport(){
        if(IS_POST){
            $post = I('post.');
            if(empty($post['content'])){
                $this->error('请填写试用报告简介');
            }
           $info=$post['image'];
            if(empty($info[0])){
                $this->error('请至少上传一张图片');
            }
            if ($info) { // 保存附件信息
                for($i=0;$i<count($info);$i++){
                    if($i==0){
                        $post['image']=$info[0];
                    }else{
                        $otherpic.=$info[$i].'|';
                    }
                }
                $post['otherpic']=substr($otherpic,0,strlen($otherpic)-1);
            }

            $result=M('TryReport')->where(array('id'=>$post['id']))->save($post);
            if($result!==false){
                $this->success('试用报告修改成功',U('/user/index/report'));
            }else{
                $this->error('试用报告修改失败,请稍候再试!');
            }
        }else{
            $data['id']=I('get.id');
            $data=M('TryReport')->where(array('id'=>$data['id']))->find();
            if(!empty($data['otherpic'])){
                $images=$data['image'].'|'.$data['otherpic'];
            }else{
                $images=$data['image'];
            }
            $data['image']=explode('|',$images);
            $this->assign('data',$data);
            $this->display();
        }
    }


    //烘焙作品显示
    public function works(){
        $where['type']=1;
        $this->assign('catname','我的烘焙作品');
        $this->assign('type', 1);
        $this->workslist($where,'works');
    }

    //参考作品显示
    public function copy(){
        $where['type']=2;
        $this->assign('catname','我的参照作品');
        $this->assign('type', 2);
        $this->workslist($where,'copy');
    }

    /**
     * 返回作品列表,上面调用
     * @param $where
     * @param $url
     */
    public function  workslist($where,$url){
        $model=M('Works');
        $status=I('get.st');
        $this->assign('act'.$status,' class="act"');
        $where['userid']=$this->userid;
        if(isset($_GET['st']) && $_GET['st']==0){
            $where['status']=false;
        }elseif(isset($_GET['st'])){
            $where['status']=$status;
        }
        $linkurl=isset($_GET['st'])?'&st='.$status:'';
        $count = $model->where($where)->count();
        $page = $this->Pages($count, 10);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = __APP__.'/user/index/'.$url.$pageurl.$linkurl;

        $field=array('type','workid','title','create_time','image','status');
        $list=$model->field($field)->where($where)->order('workid DESC')->limit($page->firstRow . ',' . $page->listRows)->select();
        $this->assign("list", $list);
        $this->assign('url',$url);
        $this->assign("Page", $page->show());
        $this->display('works');
    }

    /**
     * 删除作品
     */
    public function delworks(){
        $workid=I('infoid');
        if(empty($workid)){
            $this->error('<span>删除出错,请稍候再试!</span>');
        }
        $worksModel=M('Works');
        $workuserid=$worksModel->where(array('workid'=>$workid))->getField('userid');
        if($this->userid!=$workuserid){
            $this->error('<span>您无权限删除该作品!</span>');
        }
        $model=D('User/Works');
        if($model->deleteWorks($workid)){
            $this->success('<span>成功删除该作品!</span>');
        }else{
            $error=$model->getError();
            $this->error($error ? $error : '<span>删除作品失败!</span>');
        }
    }
    /**
     * 随拍作品
     * @param $where
     * @param $url
     */
    public function  suipai(){
        $model=M('Suipai');
        $status=I('get.st');
        $this->assign('act'.$status,' class="act"');
        $where['userid']=$this->userid;
        if(isset($_GET['st']) && $_GET['st']==0){
            $where['status']=false;
        }elseif(isset($_GET['st'])){
            $where['status']=$status;
        }
        $linkurl=isset($_GET['st'])?'&st='.$status:'';
        $count = $model->where($where)->count();
        $page = $this->Pages($count, 10);
        $pageurl='?page='.urlencode('[PAGE]');
        $page->url     = __APP__.'/user/index/suipai'.$pageurl.$linkurl;

        $field=array('id','title','create_time','image','status');
        $list=$model->field($field)->where($where)->order('id DESC')->limit($page->firstRow . ',' . $page->listRows)->select();

        $this->assign("list", $list);
        $this->assign('url','suipai');
        $this->assign("Page", $page->show());
        $this->display();
    }


    /**
     * 删除随拍作品
     */
    public function delsuipai(){
        $id=I('infoid');
        if(empty($id)){
            $this->error('<span>删除出错,请稍候再试!</span>');
        }
        $worksModel=M('Suipai');
        $workuserid=$worksModel->where(array('id'=>$id))->getField('userid');
        if($this->userid!=$workuserid){
            $this->error('<span>您无权限删除该作品!</span>');
        }
        $model=D('User/Works');
        if($model->deleteSuipai($id)){
            $this->success('<span>成功删除该作品!</span>');
        }else{
            $error=$model->getError();
            $this->error($error ? $error : '<span>删除作品失败!</span>');
        }
    }

    /**
     * 留言
     */
//     public function message(){
//         $model=M('UserMessage');
//         $type=I('get.type');
//         $type=empty($type)?'1':$type;
//         $this->type=$type;
//         $this->assign('act'.$type,' class="act"');

//         if($type==1){
//             $where['userid']=$this->userid;
//         }elseif($type==2){
//             $where['touserid']=$this->userid;
//         }

//         $linkurl=isset($_GET['type'])?'&type='.$type:'';
//         $count = $model->where($where)->count();
//         $page = $this->Pages($count, 10);
//         $pageurl='?page='.urlencode('[PAGE]');
//         $page->url     = __APP__.'/user/index/message'.$pageurl.$linkurl;

//         $field=array('infoid','content','create_time','status','id','ifread','type','userid');
//         $list=$model->field($field)->where($where)->order('id DESC')->limit($page->firstRow . ',' . $page->listRows)->select();

//         foreach($list as $k=>$v){
//             if($v['type']==2){
//                 $list[$k]['openuid']=M('User')->where(array('userid'=>$v['infoid']))->getField('openuid');
//             }
//         }
//         $this->assign("list", $list);
//         $this->assign('url','message');
//         $this->assign("Page", $page->show());
//         $this->display();
//     }
	/**
	 * yf 0921
	 * 评论信息
	 */
    public function message(){
    	$model=M('UserMessage');
    	$list1 = array();
    	$list2 = array();
    	$list3 = array();
    	$count1 = $model->where("is_del=0 and (touserid=".$this->userid." or (type=2 and infoid=".$this->userid."))")->count();
    	$field1 = array('infoid','content','create_time','status','id','ifread','type','userid','touserid');
    	$list1 = $model->field($field1)->where("is_del=0 and (touserid=".$this->userid." or (type=2 and infoid=".$this->userid."))")->select();
    	
    	$count2 = $model->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->where("A.is_del=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
    	$field2 = array('A.infoid','A.content','A.create_time','A.status','A.id','A.ifread','A.type','A.userid','A.touserid');
    	$list2 = $model->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->field($field2)->where("A.is_del=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->select();
    	
    	$count3 = $model->alias('A')->join(C('DB_PREFIX').'suipai B on A.infoid=B.id', 'LEFT')->where("A.is_del=0 and A.type=4 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
    	$field3 = array('D.infoid','D.content','D.create_time','D.status','D.id','D.ifread','D.type','D.userid','D.touserid');
    	$list3 = $model->alias('D')->join(C('DB_PREFIX').'suipai B on D.infoid=B.id', 'LEFT')->field($field3)->where("D.is_del=0 and D.type=4 and (D.touserid is NULL OR D.touserid<>".$this->userid.") and B.userid=".$this->userid)->select();
    	
    	$count4 = $model->alias('A')->join(C('DB_PREFIX').'teachlist B on A.infoid=B.teachid', 'LEFT')->where("A.is_del=0 and A.type=7 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
    	$field4 = array('D.infoid','D.content','D.create_time','D.status','D.id','D.ifread','D.type','D.userid','D.touserid');
    	$list4 = $model->alias('D')->join(C('DB_PREFIX').'teachlist B on D.infoid=B.teachid', 'LEFT')->field($field4)->where("D.is_del=0 and D.type=7 and (D.touserid is NULL OR D.touserid<>".$this->userid.") and B.userid=".$this->userid)->select();
    
    	$ypage = empty($_GET['page']) ? 1 : intval($_GET['page']);
    	$set_read = $this->set_read_status('message');
    	$all_count = $this->get_msg_num();
    //	$count = $all_count['message'];
    	$count = $count1 + $count2 + $count3 + $count4;
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/message'.$pageurl;
    	$arr = array();
    	if($list1)
    	{
    		$arr = array_merge_recursive($list1);
    	}
    	if($list2)
    	{
    		if($arr)
    		{
    			$arr = array_merge_recursive($arr, $list2);
    		}
    		else 
    		{
    			$arr = array_merge_recursive($list2);
    		}
    	}
    	if($list3)
    	{
    		if($arr)
    		{
    			$arr = array_merge_recursive($arr, $list3);
    		}
    		else 
    		{
    			$arr = array_merge_recursive($list3);
    		}
    	}
    	if($list4)
    	{
    	    if($arr)
    	    {
    	        $arr = array_merge_recursive($arr, $list4);
    	    }
    	    else
    	    {
    	        $arr = array_merge_recursive($list4);
    	    }
    	}
    	
    //	$arr = array_merge_recursive($list1, $list2, $list3);
    	usort($arr, function($a, $b) {
    		$al = $a['id'];
    		$bl = $b['id'];
    		if ($al == $bl)
    			return 0;
    		return ($al > $bl) ? -1 : 1;
    	});
    	
    	$list = array();
    	if($arr)
    	{
    		$start = ($ypage-1)*$page->listRows;
    		for($i = $start; $i < ($start + $page->listRows); $i++)
    		{
    			if(!empty($arr[$i]))
    			{
    				$list[] = $arr[$i];
    			}
    		}
    	
	    	foreach($list as $k=>$v){
	    		if($v['type'] == 1)
	    		{
	    			$list[$k]['msg'] = "在你的烘焙作品";
	    			if(!empty($v['touserid']))
	    			{
	    				$list[$k]['msg'] = "回复了你在烘焙作品";
	    			}
	    		}
	    		if($v['type']==2)
	    		{
	    			$list[$k]['msg'] = "在";
	    			$list[$k]['openuid']=M('User')->where(array('userid'=>$v['infoid']))->getField('openuid');
	    			if(!empty($v['touserid']))
	    			{
	    				$list[$k]['msg'] = "回复了你在";
	    			}
	    		}
	    		if($v['type'] == 3)
	    		{
	    			$list[$k]['msg'] = "在你的试用报告";
	    			if(!empty($v['touserid']))
	    			{
	    				$list[$k]['msg'] = "回复了你在试用报告";
	    			}
	    		}
	    		if($v['type'] == 4)
	    		{
	    			$list[$k]['msg'] = "在你的随拍作品";
	    			if(!empty($v['touserid']))
	    			{
	    				$list[$k]['msg'] = "回复了你在随拍作品";
	    			}
	    		}
	    		if($v['type'] == 5)
	    		{
	    			$list[$k]['msg'] = "在你的新闻评论";
	    			if(!empty($v['touserid']))
	    			{
	    				$list[$k]['msg'] = "回复了你在新闻评论";
	    			}
	    		}
	    		if($v['type'] == 6)
	    		{
	    			$list[$k]['msg'] = "在你的活动评论";
	    			if(!empty($v['touserid']))
	    			{
	    				$list[$k]['msg'] = "回复了你在活动评论";
	    			}
	    		}
	    		if($v['type'] == 7)
	    		{
	    		    $list[$k]['msg'] = "在你的话题文章";
	    		    if(!empty($v['touserid']))
	    		    {
	    		        $list[$k]['msg'] = "回复你再话题文章";
	    		    }
	    		}
	    		$list[$k]['content'] = hy_substr($v['content'], 25, true);
	    		if($v['userid'] == 0)
	    		{
	    			$user['nickname'] = "烘焙圈";
	    		}
	    		else 
	    		{
	    			$user = M('User')->where(array('userid' => $v['userid']))->field("nickname, uavatar, openuid")->find();
	    		}
	    		$list[$k]['user'] = $user;
	    	}
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);
    	$this->assign('url','message');
    	$this->assign("act", "message");
    	$this->assign("Page", $page->show());
    	$this->display();
    }
    /**
     * 点赞及收藏
     */
    public function digfav()
    {
    	$dig = M('Dig');
    	$fav = M('UserFavorite');
    	$ypage = I('get.page');
    	if(empty($ypage))
    	{
    		$ypage = 1;
    	}
    	//$count = $this->get_digfav_num();
    	
    	$set_read = $this->set_read_status('digfav');
    	$all_count = $this->get_msg_num();
    //	$count = $all_count['digfav'];
    	$dig_count = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.is_del=0", array($this->userid))->count();
    	$fav_count = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.is_del=0", array($this->userid))->count();
    	$count = $dig_count + $fav_count;
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/digfav'.$pageurl;
    	
    	$dig_field = array('A.id', 'A.userid' => 'touser', 'A.digtype', 'A.create_time', 'B.workid', 'B.title', 'B.type', 'B.image', 'B.userid', 'B.copyid');
    	$dig_info = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->field($dig_field)->where("B.userid=%d and A.status=1 and A.is_del=0", array($this->userid))->select();
    	$dig_info = $this->set_arr($dig_info, "dig");
    	
    	$fav_field = array('A.id', 'A.userid' => 'touser', 'A.create_time', 'B.workid', 'B.title', 'B.type', 'B.image', 'B.userid', 'B.copyid');
    	$fav_info = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->field($fav_field)->where("B.userid=%d and A.status=1 and A.is_del=0", array($this->userid))->select();
    	$fav_info = $this->set_arr($fav_info, "fav");
    	
    	$yarr = array();
    	if($dig_info)
    	{
    		$yarr = array_merge_recursive($dig_info);
    	}
    	if($fav_info)
    	{
    		if($yarr)
    		{
    			$yarr = array_merge_recursive($yarr, $fav_info);
    		}
    		else 
    		{
    			$yarr = array_merge_recursive($fav_info);
    		}
    	}
    	
    	usort($yarr, function($a, $b) {
    		$al = $a['create_time'];
    		$bl = $b['create_time'];
    		if ($al == $bl)
    			return 0;
    		return ($al > $bl) ? -1 : 1;
    	});
    	
    	$list = array();
    	$start = ($ypage-1)*$page->listRows;
    	for($i = $start; $i < ($start + $page->listRows); $i++)
    	{
    		if(!empty($yarr[$i]))
    		{
    			$list[] = $yarr[$i];
    		}
    	}
    	
    	foreach($list as $k => $v)
    	{
    		$user = M('User')->where(array("userid" => $v['touser']))->find();
    		$list[$k]['nickname'] = $user['nickname'];
    		$list[$k]['openuid'] = $user['openuid'];
    		$list[$k]['uavatar'] = $user['uavatar'];
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);
    	$this->assign("act", "digfav");
    	$this->assign("Page", $page->show());
    	$this->display();
    }
    
    public function get_digfav_num()
    {
    	$dig = M('Dig');
    	$fav = M('UserFavorite');
    	$dig_count = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->count();
    	$fav_count = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->count();
    	$count = $dig_count + $fav_count;
    	return $count;
    }
    
    public function set_arr($arr, $type)
    {
    	if(empty($arr))
    	{
    		return array();
    	}
    	else
    	{
    		foreach($arr as $k => $v)
    		{
    			$arr[$k]['type_name'] = $type;
    		}
    	}
    	return $arr;
    }
    /**
     * 关注
     */
    public function fans()
    {
    	$model = M('UserFans');
    	//$count = $model->where("ifread=0 and userid=%d and status=1", array($this->userid))->count();
    	$set_read = $this->set_read_status('fans');
    	$all_count = $this->get_msg_num();
    	$count = M('UserFans')->where("is_del=0 and userid=%d and status=1", array($this->userid))->count();
    	
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/fans'.$pageurl;
    	$field = array('id', 'myid', 'create_time');
    	$list = $model->field($field)->where("is_del=0 and userid=%d and status=1", array($this->userid))->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
    	if($list)
    	{
    		foreach($list as $k => $v)
    		{
    			$user = M('User')->where(array("userid" => $v['myid']))->find();
    			$list[$k]['nickname'] = $user['nickname'];
    			$list[$k]['openuid'] = $user['openuid'];
    			$list[$k]['uavatar'] = $user['uavatar'];
    		}
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);
    	$this->assign("Page", $page->show());
    	$this->assign("act", "fans");
    	$this->display();
    }
    
    public function pro()
    {
    	$ypage = I('get.page');
    	if(empty($ypage))
    	{
    		$ypage = 1;
    	}
    	$suipai = M('Suipai');
    	$works = M('Works');
//     	$suipai_count = $suipai->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
//     	$works_count = $works->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
//     	$count = $suipai_count + $works_count;
		$set_read = $this->set_read_status('pro');
    	$all_count = $this->get_msg_num();
    	
    	$suipai_count = M('Suipai')->where("status!=0 and is_del=0 and userid=%d", array($this->userid))->count();
    	$works_count = M('Works')->where("status!=0 and is_del=0 and userid=%d", array($this->userid))->count();
    	$count = $suipai_count + $works_count;
    	
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/pro'.$pageurl;
    	
    	$suipai_info = $suipai->where("status!=0 and is_del=0 and userid=%d", array($this->userid))->order('create_time desc')->select();
    	$suipai_info = $this->set_arr($suipai_info, "suipai");
    	$works_info = $works->where("status!=0 and is_del=0 and userid=%d", array($this->userid))->order('create_time desc')->select();
    	$works_info = $this->set_arr($works_info, "works");
    	//print_r($works_info);
    	
    	$yarr = array();
    	if($suipai)
    	{
    		$yarr = array_merge_recursive($suipai_info);
    	}
    	if($works_info)
    	{
    		if($yarr)
    		{
    			$yarr = array_merge_recursive($yarr, $works_info);
    		}
    		else
    		{
    			$yarr = array_merge_recursive($works_info);
    		}
    	}
    	
    	usort($yarr, function($a, $b) {
    		$al = $a['create_time'];
    		$bl = $b['create_time'];
    		if ($al == $bl)
    			return 0;
    		return ($al > $bl) ? -1 : 1;
    	});
    		 
    	$list = array();
    	$start = ($ypage-1)*$page->listRows;
    	for($i = $start; $i < ($start + $page->listRows); $i++)
    	{
    		if(!empty($yarr[$i]))
    		{
    			$list[] = $yarr[$i];
    		}
    	}
    	
    	foreach($list as $k => $v)
    	{
    		if($v['type_name'] == 'suipai')
    		{
    			$list[$k]['type'] = 4;
    		}
    		else 
    		{
    			$list[$k]['type'] = 1;
    		}
    		if(empty($v['modify_time']))
    		{
    			$list[$k]['modify_time'] = $v['create_time'];
    		}
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);
    	$this->assign("Page", $page->show());
    	$this->assign("act", "pro");
    	$this->display();
    }
    
    /**
     * 参考作品
     */
    public function copypro()
    {
    	$works = M('Works');
   // 	$where = "A.ifreadto=0 and B.userid=".$this->userid;
   // 	$count = $works->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->count();
   		
    	$set_read = $this->set_read_status('copypro');
   		$all_count = $this->get_msg_num();
   		
   		$where = "A.is_delto=0 and B.userid=".$this->userid;
   		$count = $works->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->count();
    	
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/copypro'.$pageurl;
    	
    	$list = $works->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->field("A.workid as copywork, A.userid as copyuser, A.image as copyimg, A.create_time, B.workid, B.title")->order('create_time DESC')->limit($page->firstRow . ',' . $page->listRows)->select();
    	if($list)
    	{
    		foreach($list as $k => $v)
    		{
    			$user = M('User')->field("nickname, openuid, uavatar")->where(array('userid' => $v['copyuser']))->find();
    			$list[$k]['nickname'] = $user['nickname'];
    			$list[$k]['openuid'] = $user['openuid'];
    			$list[$k]['uavatar'] = $user['uavatar'];
    		}
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);
    	$this->assign("act", "copypro");
    	$this->assign("Page", $page->show());
    	$this->display();
    }
	/**
	 * 积分
	 */
    public function score()
    {
    	$score = M('UserDynamic');
    	
    	//$count = $score->where("status=1 and ifread=0 and userid=%d", array($this->userid))->count();
    	
    	$set_read = $this->set_read_status('score');
    	$all_count = $this->get_msg_num();
    	
    	$count = M('UserDynamic')->where("status=1 and is_del=0 and userid=%d", array($this->userid))->count();
    	//$count = $all_count['score'];
    	
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/score'.$pageurl;
    	
    	$list = $score->where("status=1 and is_del=0 and userid=%d", array($this->userid))->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
    	if($list)
    	{
    		foreach($list as $k => $v)
    		{
    			if($v['action'] == 'workadd' || $v['action'] == 'worksindex')
    			{
    				$list[$k]['type'] = 1;
    				$list[$k]['image'] = M('Works')->where(array('workid' => $v['infoid']))->getField("image");
    				$list[$k]['copy_type'] = M('Works')->where(array('workid' => $v['infoid']))->getField("type");
    			}
    			if($v['action'] == 'spadd')
    			{
    				$list[$k]['type'] = 4;
    				$list[$k]['image'] = M('Suipai')->where(array('id' => $v['infoid']))->getField("image");
    			}
    			if($v['action'] == 'gift')
    			{
    				$list[$k]['image'] = M('Gifts')->where(array('id' => $v['infoid']))->getField("image");
    			}
    		}
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);
    	$this->assign("act", "score");
    	$this->assign("Page", $page->show());
    	$this->display();
    }
    /**
     * 试用
     */
    public function listtry()
    {
    	$try = M('TryApply');
    	
    	//$count = $try->where('status <> 0 and userid='.$this->userid." and ifread=0")->count();
    	$set_read = $this->set_read_status('listtry');
    	$all_count = $this->get_msg_num();
    	
    	$count = M('TryApply')->where('status <> 0 and userid='.$this->userid." and is_del=0")->count();
    	//$count = $all_count['listtry'];
    	
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/listtry'.$pageurl;
    	$list = $try->alias("A")->join(C('DB_PREFIX')."try_items B ON A.tryid=B.tryid", "LEFT")->field('A.id, A.tryid, A.userid, A.status, B.title, A.create_time, B.image')->where('A.status <> 0 and A.userid='.$this->userid." and A.is_del=0")->order('A.create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
    	
    	if($list)
    	{
    		foreach($list as $k => $v)
    		{
    			$user = M('User')->where(array('userid' => $this->userid))->field('nickname, openuid, uavatar')->find();
    			$list[$k]['nickname'] = $user['nickname'];
    			$list[$k]['openuid'] = $user['openuid'];
    			$list[$k]['uavatar'] = $user['uavatar'];
    		}
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);
    	$this->assign("Page", $page->show());
    	$this->assign("act", "listtry");
    	$this->display();
    }
    
    /**
     * 官方通知
     */
    public function sysmsg()
    {
    	$sys = M('Sysmsg');
    	
    	$ids = $sys->where('status=1 and sendtype=1 and (userid='.$this->userid." or userid is null) and create_time > '1438358400'")->order('create_time desc')->select();
    	if($ids)
    	{
    		$arr = array();
    		foreach($ids as $k => $v)
    		{
    			$temp_type = M('SysmsgLog')->where("sysid=".$v['id']." and userid=".$this->userid)->getField('is_del');
    			if(!isset($temp_type))
    			{
    				$info['sysid'] = $v['id'];
    				$info['userid'] = $this->userid;
    				$info['ifread'] = 0;
    				M('SysmsgLog')->data($info)->add();
    				$arr[] = $v;
    			}
    			if($temp_type == 0)
    			{
    				$arr[] = $v;
    			}
    		}
    	}
    	
    	$ypage = I('get.page');
    	$ypage = empty($ypage) ? 1 : $ypage;
    	$set_read = $this->set_read_status('sysmsg');
    	$all_count = $this->get_msg_num();
    	$count = count($arr);
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/sysmsg'.$pageurl;
    	$list = array();
    	$start = ($ypage-1)*$page->listRows;
    	for($i = $start; $i < ($start + $page->listRows); $i++)
    	{
    		if(!empty($arr[$i]))
    		{
    			$arr[$i]['logid'] = M('SysmsgLog')->where('sysid='.$arr[$i]['id']." and userid=".$this->userid)->getField("id");
    			$list[] = $arr[$i];
    		}
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);//print_r($list);
    	$this->assign("Page", $page->show());
    	$this->assign("act", "sysmsg");
    	$this->display();
    }
    
    /**
     * 发件箱
     */
    public function sendmsg()
    {
    	$sysmsg = M('Sysmsg');
    	
     	$where = "status=1 and sendtype=2 and userid=".$this->userid." and ifread=0";
//     	$count = $sysmsg->where($where)->count();
		$all_count = $this->get_msg_num();
		$count = $all_count['sendmsg'];
    	$page = $this->Pages($count, 10);
    	$pageurl='?page='.urlencode('[PAGE]');
    	$page->url     = __APP__.'/user/index/sendmsg'.$pageurl;
    	
    	$list = $sysmsg->where($where)->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
    	if($list)
    	{
    		foreach($list as $k => $v)
    		{
    			$user = M('User')->where(array('userid' => $v['userid']))->find();
    			$list[$k]['nickname'] = $user['nickname'];
    			$list[$k]['openuid'] = $user['openuid'];
    			$list[$k]['uavatar'] = $user['uavatar'];
    		}
    	}
    	$this->assign("all_count", $all_count);
    	$this->assign("list", $list);
    	$this->assign("type", "send");
    	$this->assign("Page", $page->show());
    	$this->assign("count", $count);
    	$this->display();
    }
    
    public function get_msg_num()
    {
    	$arr = array();
    	
    	$message1 = M('UserMessage')->where("ifread=0 and (touserid=".$this->userid." or (type=2 and infoid=".$this->userid."))")->count();
    	$message2 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->where("A.ifread=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
    	$message3 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'suipai B on A.infoid=B.id', 'LEFT')->where("A.ifread=0 and A.type=4 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
    	$message4 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'teachlist B on A.infoid=B.teachid', 'LEFT')->where("A.ifread=0 and A.type=7 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
    	$arr['message'] = $message1 + $message2 + $message3 + $message4;
    	
    	$arr['digfav'] = $this->get_digfav_num();
    	
    	$arr['fans'] = M('UserFans')->where("ifread=0 and userid=%d and status=1", array($this->userid))->count();
    	
    	$suipai_count = M('Suipai')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
    	$works_count = M('Works')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
    	$arr['pro'] = $suipai_count + $works_count;
    	
    	$where = "A.ifreadto=0 and B.userid=".$this->userid;
    	$arr['copypro'] = M('Works')->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->count();
    	
    	$arr['score'] = M('UserDynamic')->where("status=1 and ifread=0 and userid=%d", array($this->userid))->count();
    	
    	$arr['listtry'] = M('TryApply')->where('status <> 0 and userid='.$this->userid." and ifread=0")->count();
    	
    	$yarr = array();
    	$ids = M('Sysmsg')->where('status=1 and sendtype=1 and (userid='.$this->userid." or userid is null) and create_time > '1438358400'")->order('create_time desc')->select();
    	if($ids)
    	{
    		foreach($ids as $k => $v)
    		{
    			$temp_type = M('SysmsgLog')->where("sysid=".$v['id']." and userid=".$this->userid)->getField('ifread');
    			if(!isset($temp_type))
    			{
    				$info['sysid'] = $v['id'];
    				$info['userid'] = $this->userid;
    				$info['ifread'] = 0;
    				$info['is_del'] = 0;
    				M('SysmsgLog')->data($info)->add();
    				$yarr[] = $v;
    			}
    			if($temp_type == 0)
    			{
    				$yarr[] = $v;
    			}
    		}
    	}
    	$arr['sysmsg'] = count($yarr);
    	
    	$where2 = "status=1 and sendtype=2 and userid=".$this->userid." and ifread=0";
    	$arr['sendmsg'] = M('Sysmsg')->where($where2)->count();
    	
    	return $arr;
    }
    
    public function set_read_status($type)
    {
    	if($type == 'message')
    	{
    		$message1 = M('UserMessage')->where("ifread=0 and (touserid=".$this->userid." or (type=2 and infoid=".$this->userid."))")->field('id')->select();
    		$message2 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->where("A.ifread=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->field('A.id')->select();
    		$message3 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'suipai B on A.infoid=B.id', 'LEFT')->where("A.ifread=0 and A.type=4 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->field('A.id')->select();
    		$message4 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'teachlist B on A.infoid=B.teachid', 'LEFT')->where("A.ifread=0 and A.type=7 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->field('A.id')->select();
    	//	print_r($message1);echo "<br>";print_r($message2);echo "<br>";print_r($message3);echo "<br>";
    		$arr = array();
    		if(!empty($message1))
    		{
    			$arr = array_merge_recursive($message1);
    		}
    		if(!empty($message2))
    		{
    			if(!empty($arr))
    			{
    				$arr = array_merge_recursive($arr, $message2);
    			}
    			else 
    			{
    				$arr = array_merge_recursive($message2);
    			}
    		}
    		if(!empty($message3))
    		{
    			if(!empty($arr))
    			{
    				$arr = array_merge_recursive($arr, $message3);
    			}
    			else
    			{
    				$arr = array_merge_recursive($message3);
    			}
    		}
    		if(!empty($message4))
    		{
    		    if(!empty($arr))
    		    {
    		    				$arr = array_merge_recursive($arr, $message4);
    		    }
    		    else
    		    {
    		    				$arr = array_merge_recursive($message4);
    		    }
    		}
    		if(!empty($arr))
    		{
    			foreach($arr as $k => $v)
    			{
    				M('UserMessage')->where(array('id' => $v['id']))->save(array('ifread' => 1));
    			}
    		}
    	}
    	if($type == 'digfav')
    	{
    		$dig = M('Dig');
    		$fav = M('UserFavorite');
    		$dig_count = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->field('id')->select();
    		$fav_count = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->field('id')->select();
    		if(!empty($dig_count))
    		{
    			foreach($dig_count as $dk => $dv)
    			{
    				$dig->where(array('id' => $dv['id']))->save(array('ifread' => 1));
    			}
    		}
    		if(!empty($fav_count))
    		{
    			foreach($fav_count as $fk => $fv)
    			{
    				$fav->where(array('id' => $fv['id']))->save(array('ifread' => 1));
    			}
    		}
    	}
    	if($type == 'fans')
    	{
    		$fans = M('UserFans')->where("ifread=0 and userid=%d and status=1", array($this->userid))->field('id')->select();
    		if(!empty($fans))
    		{
    			foreach($fans as $k => $v)
    			{
    				M('UserFans')->where(array('id' => $v['id']))->save(array('ifread' => 1));
    			}
    		}
    	}
    	if($type == 'pro')
    	{
    		$suipai_count = M('Suipai')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->field('id')->select();
    		$works_count = M('Works')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->field('workid')->select();
    		if(!empty($suipai_count))
    		{
    			foreach($suipai_count as $sk => $sv)
    			{
    				M('Suipai')->where(array('id' => $sv['id']))->save(array('ifread' => 1));
    			}
    		}
    		if(!empty($works_count))
    		{
    			foreach($works_count as $wk => $wv)
    			{
    				M('Works')->where(array('workid' => $wv['workid']))->save(array('ifread' => 1));
    			}
    		}
    	}
    	if($type == 'copypro')
    	{
    		$where = "A.ifreadto=0 and B.userid=".$this->userid;
    		$copypro = M('Works')->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->field('A.workid')->select();
    		if(!empty($copypro))
    		{
    			foreach($copypro as $k => $v)
    			{
    				M('Works')->where(array('workid' => $v['workid']))->save(array('ifreadto' => 1));
    			}
    		}
    	}
    	if($type == 'score')
    	{
    		$score = M('UserDynamic')->where("status=1 and ifread=0 and userid=%d", array($this->userid))->field('id')->select();
    		if(!empty($score))
    		{
    			foreach($score as $k => $v)
    			{
    				M('UserDynamic')->where(array('id' => $v['id']))->save(array('ifread' => 1));
    			}
    		}
    	}
    	if($type == 'listtry')
    	{
    		$try = M('TryApply')->where('status <> 0 and userid='.$this->userid." and ifread=0")->field('id')->select();
    		if(!empty($try))
    		{
    			foreach($try as $k => $v)
    			{
    				M('TryApply')->where(array('id' => $v['id']))->save(array('ifread' => 1));
    			}
    		}
    	}
    	if($type == 'sysmsg')
    	{
    		$ids = M('Sysmsg')->where('status=1 and sendtype=1 and (userid='.$this->userid." or userid is null) and create_time > '1438358400'")->order('create_time desc')->select();
    		if($ids)
    		{
    			$arr = array();
    			foreach($ids as $k => $v)
    			{
    				$temp_type = M('SysmsgLog')->where("sysid=".$v['id']." and userid=".$this->userid)->getField('ifread');
    				if(!isset($temp_type))
    				{
    					$info['sysid'] = $v['id'];
    					$info['userid'] = $this->userid;
    					$info['ifread'] = 0;
    					M('SysmsgLog')->data($info)->add();
    					$arr[] = $v;
    				}
    				if($temp_type == 0)
    				{
    					$arr[] = $v;
    				}
    			}
    		}
    		if(!empty($arr))
    		{
    			foreach($arr as $k => $v)
    			{
    				M('SysmsgLog')->where(array('userid' => $this->userid, 'sysid' => $v['id']))->save(array('ifread' => 1));
    			}
    		}
    	}
    }
    
    /**
     * 隐藏提醒功能
     */
    public function msgdel()
    {
    	$id = $_POST['yid'];
    	$type = $_POST['ytype'];
    	$arr = array();
    	
    	if(!is_array($id) && !is_array($type))
    	{
    		$temp_id = $id;unset($id);
    		$temp_type = $type;unset($type);
    		$id[] = $temp_id;
    		$type[] = $temp_type;
    	}
    	
    	if(is_array($id) && is_array($type))
    	{
    		$count_id = count($id);
    		$count_type = count($type);
    		if($count_id == $count_type)
    		{
    			for($i = 0; $i < $count_id; $i++)
    			{
    				$arr[$i]['id'] = $id[$i];
    				$arr[$i]['type'] = $type[$i];
    				$arr[$i]['ifread'] = 'is_del';
    				$arr[$i]['name'] = 'id';
    				if($type[$i] == 'Works')
    				{
    					$arr[$i]['name'] = 'workid';
    				}
    				if($type[$i] == 'Copy')
    				{
    					$arr[$i]['name'] = 'workid';
    					$arr[$i]['type'] = 'Works';
    					$arr[$i]['ifread'] = 'is_delto';
    				}
    			}
    		}
    	}
    	
    	if(empty($arr))
    	{
    		$this->error("删除失败");
    	}
    	foreach($arr as $k => $v)
    	{
    		$data = array();
    		$data[$v['ifread']] = 1;
    		M($v['type'])->where(array($v['name'] => $v['id']))->save($data);
    	}
    	$this->success("删除成功");
    }

    /**
     * 删除留言操作
     */
    public function delmsg(){
        $msgid=I('get.infoid');
        if(empty($msgid)){
            $this->_empty();
        }
        $where['userid']=$this->userid;
        $where['id']=$msgid;
        $result=M('UserMessage')->where($where)->delete();
        if($result){
            $this->success('留言删除成功');
        }else{
            $this->error('留言删除失败');
        }
    }

    /**
     * 阅读留言
     */

    public function readmsg(){
        $msgid=I('get.id');
        if(empty($msgid)){
            $this->_empty();
        }
        $model=M('UserMessage');
        $msg=$model->field('userid,infoid,touserid,type')->where(array('id'=>$msgid))->find();
        $msg['openuid']=M('User')->where(array('userid'=>$msg['infoid']))->getField('openuid');
        $model->where(array('id'=>$msgid))->save(array('ifread'=>true));

        $this->redirect('/'.getMsgLink($msg['type'],$msg['infoid'],$msg['openuid']).'#msg');
        exit;
        $list=$model->field("userid,infoid,content,create_time,id,touserid")->where(array('infoid'=>$msg['infoid'],'userid'=>$msg['userid'],'touserid'=>$this->userid))->order("id ASC")->select();
        foreach($list as $key=>$v){
            $model->where(array('id'=>$v['id']))->save(array('ifread'=>true));
            $list[$key]['user']=M('User')->field('nickname,openuid')->where(array('userid'=>$v['userid']))->find();
        }
        $this->assign('list',$list);
        $this->display();
    }


    /**
     * 系统消息
     */
//     public function sysmsg(){
//         $model=M('Sysmsg');
//         $type=I('get.type');
//         $type=empty($type)?'1':$type;
//         $this->type=$type;
//         $this->assign('act'.$type,' class="act"');

//         if($type==1){
//             $where='status=true and sendtype=1 and create_time>='.service("Passport")->getInfo()['create_time'].' and type=1 or userid='.$this->userid.' and type<>0';
//         }elseif($type==2){
//             $where='status=true and sendtype=2 and userid='.$this->userid;
//         }
		
//         $linkurl=isset($_GET['type'])?'&type='.$type:'';

//         $count = $model->where($where)->count();
//         $page = $this->Pages($count, 10);
//         $pageurl='?page='.urlencode('[PAGE]');
//         $page->url     = __APP__.'/user/index/sysmsg'.$pageurl.$linkurl;

//         $field=array('id','title','create_time','content','userid','ifread','type');
//         $list=$model->field($field)->where($where)->order('id DESC')->limit($page->firstRow . ',' . $page->listRows)->select();

//         foreach($list as $k=>$v){
//             if($v['type']==2){
//                 $list[$k]['openuid']=M('User')->where(array('userid'=>$v['infoid']))->getField('openuid');
//             }
//         }
//         $this->assign("list", $list);
//         $this->assign('url','sysmsg');
//         $this->assign("Page", $page->show());
//         $this->display();

//     }


    /**
     * 阅读站内信
     */
    public function readsysmsg(){
        $id=I('get.id');
        $model=M('Sysmsg');
        if(empty($id)){
            $this->error('您访问的页面不存在!');
        }
        $data=$model->where(array('id'=>$id))->find();
        if($data['type']==2){
            if($model->where(array('userid'=>$this->userid,'id'=>$id))->count()<1){
                $this->error('您无权查看此页面!');
            }

        }
        if($data){
            $model->where(array('id'=>$id))->save(array('ifread'=>true));
            $this->assign('data',$data);
            $this->display();
        }
    }

    /**
     * 申请成为烘焙师
     */
    public function userRequest(){
        $infoid=I('get.infoid');
        if($infoid!=$this->userid){
            $this->error('申请出错,请稍候再试!');
        }
        $data['ifrequest']=true;
        if(M('User')->where(array('userid'=>$infoid))->save($data)){
            $this->success('烘焙师申请成功,请等待审核!');
        }else{
            $this->error('烘焙师申请失败,请稍候再试!');
        }
    }


    /**
     * 写站内信
     */

    public function writemsg(){
        if(IS_POST){
            $post=I('post.');
            if(empty($post['title'])){
                $this->error('请填写站内信主题');
            }
            if(empty($post['content'])){
                $this->error('请填写站内信内容');
            }
            $post['userid']=$this->userid;
            $post['type']=0; //1表示系统消息,2表示会员消息
            $post['sendtype']=2;// 1表示收到,2表示发送
            $post['ifread']=0;//yf 0929
            $post['status']=true;
            $post['create_time']=time();
            $result=M('Sysmsg')->add($post);
            if($result){
                $this->success('成功发布站内信',U('sendmsg'));
            }else {
                $this->error('站内信发布失败');
            }
        }else{
            $this->display();
        }

    }

	public function repwd()
	{
		if($_POST)
		{
			$post = I('post.');
			$oldpwd = $post['oldpwd'];
			$newpwd = $post['newpwd'];
			$newpwd2 = $post['newpwd2'];
			$vcode = $post['vCode'];
			if(empty($oldpwd))
			{
				$this->error("请输入旧密码");
			}
			if(empty($newpwd))
			{
				$this->error("请输入新密码");
			}
			if(empty($newpwd2))
			{
				$this->error("请输入确认密码");
			}
			if($newpwd != $newpwd2)
			{
				$this->error("输入的两次新密码不一致");
			}
			if($oldpwd == $newpwd)
			{
				$this->error("输入的旧密码与新密码不能一样");
			}
			if (false == $this->verify($vcode, 'userpwd')) {
	            $this->error('验证码错误，请重新输入！');
	        }
	        if (false == isMin($newpwd, 6)) {
	        	$this->error('输入的新密码不能小于6位！');
	        }
	        
	        $user = M('User')->where(array('userid' => $this->userid))->field("uname, upassword, authkey")->find();
	        if(empty($user))
	        {
	        	$this->error("系统错误");
	        }
	        $temp_pwd = D("User/User")->encryption($user['uname'], $oldpwd, $user['authkey']);
	        if($temp_pwd != $user['upassword'])
	        {
	        	$this->error("输入的旧密码错误");
	        }
	        
	        $res = D('User/User')->ChangePassword($user['uname'], $newpwd);
	        if($res)
	        {
	        	$this->success("修改成功", "/user/index/logout");
	        }
	        else 
	        {
	        	$this->error("修改失败");
	        }
	        //$encrypt = genRandomString(6);
		}
		else
		{
			$this->display();
		}
	}
	
	public function teach()
	{
	    if(IS_POST)
	    {
	        $post['ifds'] = 2;
	        $id = M('User')->where(array('userid' => $this->userid))->save($post);
	        if($id)
	        {
	            $this->success("提交成功");
	        }
	        else
	        {
	            $this->error("提交失败");
	        }
	    }
	    else 
	    {
	        $config = cache('Config');
	        $this->teach = $config['teach'];
	        if(!$this->userid)
	        {
	            $this->error("请先登录", U('/user/login'));
	        }
	        $user = M('User')->where(array('userid' => $this->userid))->field('ifds')->find();
	        $this->assign("config", $this->teach);
	        $this->assign("user", $user);
	        $this->display();
	    }
	}

}